package admin;

import com.fasterxml.jackson.databind.ObjectMapper;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;

@WebServlet("/adminGetInfoServlet")
public class adminGetInfoServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        HttpSession session = request.getSession();
        String action = request.getParameter("action");

        // 验证管理员身份
        String adminUsername = (String) session.getAttribute("adminUsername");
        String userType = (String) session.getAttribute("userType");

        if (adminUsername == null || !"admin".equals(userType)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.print("{\"error\": \"未授权\"}");
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            switch (action) {
                case "logout":
                    session.invalidate();
                    out.print("{\"message\": \"退出成功\"}");
                    break;

                case "getUsers":
                    List<Map<String, Object>> users = new ArrayList<>();
                    try (PreparedStatement stmt = conn.prepareStatement("SELECT id, username, email, avatar_url FROM users");
                         ResultSet rs = stmt.executeQuery()) {
                        while (rs.next()) {
                            Map<String, Object> user = new HashMap<>();
                            user.put("id", rs.getInt("id"));
                            user.put("username", rs.getString("username"));
                            user.put("email", rs.getString("email"));
                            user.put("avatarUrl", rs.getString("avatar_url"));
                            users.add(user);
                        }
                    }
                    out.print(mapper.writeValueAsString(users));
                    break;

                case "getProducts":
                    List<Map<String, Object>> products = new ArrayList<>();
                    try (PreparedStatement stmt = conn.prepareStatement("SELECT id, category_id, name, price, image_url FROM products");
                         ResultSet rs = stmt.executeQuery()) {
                        while (rs.next()) {
                            Map<String, Object> product = new HashMap<>();
                            product.put("id", rs.getInt("id"));
                            product.put("category", rs.getInt("category_id"));
                            product.put("name", rs.getString("name"));
                            product.put("price", rs.getDouble("price"));
                            product.put("imageUrl", rs.getString("image_url"));
                            products.add(product);
                        }
                    }
                    out.print(mapper.writeValueAsString(products));
                    break;

                case "deleteUser":
                    int userId = Integer.parseInt(request.getParameter("userId"));
                    try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM users WHERE id = ?")) {
                        stmt.setInt(1, userId);
                        int rows = stmt.executeUpdate();
                        if (rows > 0) {
                            out.print("{\"message\": \"用户删除成功\"}");
                        } else {
                            out.print("{\"error\": \"用户删除失败\"}");
                        }
                    }
                    break;

                case "deleteProduct":
                    int productId = Integer.parseInt(request.getParameter("productId"));
                    try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM products WHERE id = ?")) {
                        stmt.setInt(1, productId);
                        int rows = stmt.executeUpdate();
                        if (rows > 0) {
                            out.print("{\"message\": \"商品删除成功\"}");
                        } else {
                            out.print("{\"error\": \"商品删除失败\"}");
                        }
                    }
                    break;

                default:
                    out.print("{\"error\": \"无效的请求\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.print("{\"error\": \"数据库错误: " + e.getMessage() + "\"}");
        }
    }
}
